package com.example.human_resource_management.config;

import com.example.human_resource_management.config.UserContextUtils;
import com.example.human_resource_management.config.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 去掉 "Bearer "
            try {
                Long empId = JwtUtils.getEmpIdFromToken(token);
                UserContextUtils.setEmpId(empId); // 存入 ThreadLocal
                return true;
            } catch (Exception e) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token 无效");
                return false;
            }
        }
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "请提供 Token");
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserContextUtils.clear(); // 清除 ThreadLocal
    }
}